<template>
  <div class="chat-container">
    <!-- 顶部导航栏 -->
    <div class="header">
      <div class="logo"></div>
      <div class="user-info">
        <div class="avatar-container" @click="showAvatarUploadDialog = true">
          <div class="user-avatar" :style="userAvatarStyle">
            {{ user && user.username ? user.username.slice(0, 1) : 'U' }}
          </div>
          <div class="avatar-hover-text">修改头像</div>
        </div>
        <span class="username-text">{{ user && user.username }}</span>
        <el-button type="danger" size="small" round @click="handleLogout">退出登录</el-button>
        <el-dropdown v-if="nw" trigger="click" @command="handleCommand">
          <el-button type="info" size="small" icon="el-icon-setting" circle></el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="resetExitChoice">重置退出选项</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
    
    <!-- 主体内容 -->
    <div class="main">
      <!-- 左侧用户列表 -->
      <div class="user-list">
        <!-- 群聊 -->
        <div 
          class="user-item" 
          :class="{ 'active': currentChat.type === 1, 'notification': newMessageNotification.group }"
          @click="selectChat(1, null, '群聊室')">
          <div class="avatar group-avatar">群</div>
          <div class="user-info">
            <div class="username">群聊室</div>
          </div>
        </div>
        
        <!-- 分割线 -->
        <div class="divider">
          <span>在线用户 ({{ onlineUsers.length }})</span>
        </div>
        
        <!-- 在线用户列表 -->
        <div 
          v-for="otherUser in onlineUsers"
          :key="otherUser.id"
          class="user-item"
          :class="{ 
            'active': currentChat.type === 0 && currentChat.targetId === otherUser.id,
            'notification': newMessageNotification.private[otherUser.id]
          }"
          @click="selectChat(0, otherUser.id, otherUser.username)">
          <div class="avatar online-avatar">{{ otherUser.username.slice(0, 1) }}</div>
          <div class="user-info">
            <div class="username">{{ otherUser.username }}</div>
            <div class="status online">在线</div>
          </div>
        </div>
        
        <!-- 分割线 - 离线用户 -->
        <div class="divider" v-if="offlineUsers.length > 0">
          <span>离线用户 ({{ offlineUsers.length }})</span>
        </div>
        
        <!-- 离线用户列表 -->
        <div 
          v-for="otherUser in offlineUsers"
          :key="otherUser.id"
          class="user-item"
          :class="{ 
            'active': currentChat.type === 0 && currentChat.targetId === otherUser.id,
            'notification': newMessageNotification.private[otherUser.id]
          }"
          @click="selectChat(0, otherUser.id, otherUser.username)">
          <div class="avatar offline-avatar">{{ otherUser.username.slice(0, 1) }}</div>
          <div class="user-info">
            <div class="username">{{ otherUser.username }}</div>
            <div class="status">离线</div>
          </div>
        </div>
      </div>
      
      <!-- 右侧聊天区域 -->
      <div class="chat-area">
        <!-- 聊天窗口头部 -->
        <div class="chat-header">
          <span>{{ currentChat.targetName }}</span>
        </div>
        
        <!-- 聊天消息区域 -->
        <div class="message-list" ref="messageList">
          <div v-if="currentMessages.length === 0" class="no-message">
            暂无消息，开始聊天吧
          </div>
          
          <div v-for="(message, index) in currentMessages" :key="index" class="message-item" :class="{ 'self': user && message.senderId === user.id }">
            <div class="message-avatar">{{ message.senderName ? message.senderName.slice(0, 1) : 'U' }}</div>
            <div class="message-content">
              <div class="message-info">
                <span class="message-sender">{{ message.senderName }}</span>
                <span class="message-time">{{ formatTime(message.sendTime) }}</span>
              </div>
              <div class="message-text" v-if="message.messageType === 0">
                {{ message.content }}
              </div>
              <div class="message-image" v-else-if="message.messageType === 1">
                <img :src="formatImageUrl(message.fileUrl)" @click="previewImage(message.fileUrl)" />
              </div>
              <div class="message-file" v-else-if="message.messageType === 2">
                <a :href="formatImageUrl(message.fileUrl)" target="_blank" download>
                  <i class="el-icon-document"></i>
                  {{ message.content }}
                </a>
              </div>
              <div class="message-emoji" v-else-if="message.messageType === 3">
                <span style="font-size: 24px;">{{ message.content }}</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 输入区域 -->
        <div class="input-area">
          <div class="toolbar">
            <i class="el-icon-picture-outline" @click="openImageUpload"></i>
            <i class="el-icon-paperclip" @click="openFileUpload"></i>
            <i class="el-icon-magic-stick" @click="showEmojiPicker = !showEmojiPicker"></i>
            <!-- 替换铃铛按钮，根据soundEnabled状态显示不同图标 -->
            <i :class="soundEnabled ? 'el-icon-bell' : 'el-icon-turn-off'" 
               @click="toggleSound" 
               :title="soundEnabled ? '点击禁用通知声音' : '点击启用通知声音'"
               :style="{ color: soundEnabled ? '#409EFF' : '#F56C6C' }"></i>
          </div>
          
          <!-- 表情选择器 -->
          <div class="emoji-picker" v-if="showEmojiPicker">
            <div 
              v-for="emoji in emojiList" 
              :key="emoji" 
              class="emoji-item"
              @click="insertEmoji(emoji)">
              {{ emoji }}
            </div>
          </div>
          
          <el-input
            type="textarea"
            :rows="3"
            v-model="inputMessage"
            placeholder="请输入消息，按Enter发送，Shift+Enter换行..."
            resize="none"
            @keyup.enter.native="handleEnterPress">
          </el-input>
          
          <div class="send-button">
            <el-button type="primary" @click="sendTextMessage">发送</el-button>
          </div>
          
          <!-- 隐藏的文件上传输入 -->
          <input
            type="file"
            ref="imageUploader"
            style="display: none"
            accept="image/*"
            @change="uploadImage"
          />
          <input
            type="file"
            ref="fileUploader"
            style="display: none"
            @change="uploadFile"
          />
        </div>
      </div>
    </div>
    
    <!-- 图片预览 -->
    <el-dialog :visible.sync="imagePreview.visible" append-to-body>
      <img width="100%" :src="imagePreview.url" alt="预览图片">
    </el-dialog>
    
    <!-- 头像上传对话框 -->
    <el-dialog title="修改头像" :visible.sync="showAvatarUploadDialog" width="400px">
      <div class="avatar-upload-container">
        <div class="current-avatar">
          <div class="avatar-preview" :style="userAvatarStyle">
            {{ user && user.username ? user.username.slice(0, 1) : 'U' }}
          </div>
          <p>当前头像</p>
        </div>
        
        <div class="upload-options">
          <p>选择一张图片作为头像</p>
          <el-button type="primary" @click="$refs.avatarUploader.click()">选择图片</el-button>
          <input
            type="file"
            ref="avatarUploader"
            style="display: none"
            accept="image/*"
            @change="updateUserAvatar"
          />
          <p class="tip">支持jpg、png、gif格式，文件小于5MB</p>
        </div>
      </div>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="showAvatarUploadDialog = false">取消</el-button>
        <el-button type="primary" @click="showAvatarUploadDialog = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { userApi, messageApi, fileApi } from '../utils/api'
import { mapState } from 'vuex'
import { formatImageUrl } from '../utils/image-url'
import trayManager from '../utils/tray-manager'

export default {
  name: 'Chat',
  data() {
    return {
      inputMessage: '',
      showEmojiPicker: false,
      imagePreview: {
        visible: false,
        url: ''
      },
      emojiList: ['😊', '😂', '🤣', '❤️', '👍', '😍', '😒', '😘', '🤔', '😮', '😢', '😭', '😡'],
      showAvatarUploadDialog: false,
      userAvatarStyle: {},
      userListUpdateInterval: null,
      soundEnabled: true,
      nw: typeof window !== 'undefined' && window.nw ? window.nw : undefined,
    }
  },
  computed: {
    ...mapState({
      user: state => state.user,
      userList: state => state.userList,
      currentChat: state => state.currentChat,
      messages: state => state.messages,
      newMessageNotification: state => state.newMessageNotification
    }),
    
    // 当前聊天的消息列表
    currentMessages() {
      if (this.currentChat.type === 1) {
        return this.messages.group || []
      } else {
        return this.messages.private[this.currentChat.targetId] || []
      }
    },
    
    // 过滤掉当前登录用户自己
    filteredUserList() {
      return this.userList.filter(u => u.id !== this.user.id)
    },
    
    // 在线用户数量
    onlineUserCount() {
      return this.filteredUserList.filter(u => u.online).length
    },
    
    // 在线用户列表
    onlineUsers() {
      return this.filteredUserList.filter(u => u.online)
    },
    
    // 离线用户列表
    offlineUsers() {
      return this.filteredUserList.filter(u => !u.online)
    }
  },
  watch: {
    // 监听消息变化，自动滚动到底部
    currentMessages: {
      handler() {
        this.$nextTick(() => {
          this.scrollToBottom()
        })
      },
      deep: true
    }
  },
  mounted() {
    try {
      this.initData()
      
      // 在页面卸载时关闭WebSocket连接
      window.addEventListener('beforeunload', this.closeConnection)
      
      // 初始化托盘管理器
      if (this.nw) {
        trayManager.initTray();
      }
      
      // 设置额外的本地用户列表更新，作为后备保障
      this.setupUserListUpdate();
      
      // 添加用户交互事件监听，在用户操作时更新用户列表
      this.setupUserInteractionListeners();
      
      // 添加用户交互事件，用于解锁音频
      this.setupAudioUnlockListeners();
    } catch (e) {
      console.error('挂载组件时出错:', e)
    }
  },
  activated() {
    // 组件被激活时触发更新用户列表
    if (this.$updateUserList) {
      this.$updateUserList();
    }
  },
  beforeDestroy() {
    try {
      window.removeEventListener('beforeunload', this.closeConnection)
      // 确保关闭WebSocket连接
      this.closeConnection()
      
      // 清除本地用户列表更新定时器
      this.clearUserListUpdate();
      
      // 移除用户交互事件监听
      this.removeUserInteractionListeners();
    } catch (e) {
      console.error('销毁组件时出错:', e)
    }
  },
  methods: {
    async initData() {
      try {
        // 从localStorage获取用户信息
        const userId = localStorage.getItem('userId')
        const username = localStorage.getItem('username')
        const userAvatar = localStorage.getItem('userAvatar')
        
        // 获取用户的声音设置偏好
        const savedSoundSetting = localStorage.getItem('soundEnabled');
        if (savedSoundSetting !== null) {
          this.soundEnabled = savedSoundSetting === 'true';
          console.log('已加载用户声音设置:', this.soundEnabled ? '开启' : '关闭');
        }
        
        if (!userId || !username) {
          console.warn('未找到用户信息，跳转到登录页')
          this.$router.push('/')
          return
        }
        
        // 初始化用户信息
        this.$store.dispatch('login', {
          id: Number(userId),
          username
        })
        
        // 如果有保存的头像，设置头像样式
        if (userAvatar) {
          this.userAvatarStyle = {
            backgroundImage: `url(${formatImageUrl(userAvatar)})`,
            backgroundSize: 'cover',
            backgroundPosition: 'center',
            color: 'transparent'
          }
        }
        
        // 初始化WebSocket连接
        this.$initWebSocket(userId)
        
        try {
          // 获取用户列表
          const userList = await userApi.getUserList()
          this.$store.dispatch('updateUserList', userList)
          
          // 获取群聊消息
          const groupMessages = await messageApi.getGroupMessages()
          this.$store.commit('SET_GROUP_MESSAGES', groupMessages)
        } catch (error) {
          console.error('初始化数据失败:', error)
          this.$message.error('获取用户数据失败，请刷新页面重试')
        }
      } catch (e) {
        console.error('初始化过程出错:', e)
        this.$message.error('初始化聊天界面失败，请刷新页面重试')
        this.$router.push('/')
      }
    },
    
    // 选择聊天对象
    async selectChat(type, targetId, targetName) {
      // 更新当前聊天对象
      this.$store.commit('SET_CURRENT_CHAT', { type, targetId, targetName })
      
      if (type === 0 && targetId) {
        // 如果是私聊，需要获取与该用户的私聊消息
        try {
          if (!this.messages.private[targetId]) {
            const privateMessages = await messageApi.getPrivateMessages(this.user.id, targetId)
            this.$store.commit('SET_PRIVATE_MESSAGES', { userId: targetId, messages: privateMessages })
          }
        } catch (error) {
          console.error('获取私聊消息失败:', error)
        }
      }
    },
    
    // 发送文本消息
    sendTextMessage() {
      const content = this.inputMessage.trim();
      if (!content) {
        this.$message({
          message: '消息不能为空',
          type: 'warning',
          duration: 1500
        });
        return;
      }
      
      this.sendMessage({
        content,
        messageType: 0, // 文本消息
        chatType: this.currentChat.type,
        receiverId: this.currentChat.type === 0 ? this.currentChat.targetId : null
      });
      
      this.inputMessage = '';
      this.showEmojiPicker = false;
    },
    
    // 发送消息通用方法
    sendMessage(messageData) {
      const message = {
        type: 0, // 聊天消息
        data: messageData
      }
      
      this.$sendMessage(message)
    },
    
    // 打开图片上传
    openImageUpload() {
      this.$refs.imageUploader.click()
    },
    
    // 上传图片
    async uploadImage(event) {
      const file = event.target.files[0]
      if (!file) return
      
      try {
        const res = await fileApi.upload(file)
        
        this.sendMessage({
          content: '[图片]',
          messageType: 1, // 图片消息
          chatType: this.currentChat.type,
          receiverId: this.currentChat.type === 0 ? this.currentChat.targetId : null,
          fileUrl: res.url
        })
      } catch (error) {
        console.error('上传图片失败:', error)
        this.$message.error('上传图片失败')
      } finally {
        // 清空文件输入，允许重复选择同一文件
        this.$refs.imageUploader.value = ''
      }
    },
    
    // 打开文件上传
    openFileUpload() {
      this.$refs.fileUploader.click()
    },
    
    // 上传文件
    async uploadFile(event) {
      const file = event.target.files[0]
      if (!file) return
      
      try {
        console.log('开始上传文件:', file.name);
        const res = await fileApi.upload(file)
        console.log('文件上传成功，返回数据:', res);
        
        this.sendMessage({
          content: file.name, // 使用原始文件名作为内容显示
          messageType: 2, // 文件消息
          chatType: this.currentChat.type,
          receiverId: this.currentChat.type === 0 ? this.currentChat.targetId : null,
          fileUrl: res.url
        })
      } catch (error) {
        console.error('上传文件失败:', error)
        this.$message.error('上传文件失败')
      } finally {
        // 清空文件输入，允许重复选择同一文件
        this.$refs.fileUploader.value = ''
      }
    },
    
    // 插入表情
    insertEmoji(emoji) {
      this.inputMessage += emoji
      this.showEmojiPicker = false
    },
    
    // 预览图片
    previewImage(url) {
      this.imagePreview.url = formatImageUrl(url)
      this.imagePreview.visible = true
    },
    
    // 获取文件名
    getFileName(url) {
      if (!url) return '未知文件'
      
      // 先尝试从URL中获取文件名
      const fileName = url.substring(url.lastIndexOf('/') + 1)
      // 移除可能存在的查询参数
      return fileName.split('?')[0]
    },
    
    // 格式化图片URL
    formatImageUrl(url) {
      return formatImageUrl(url)
    },
    
    // 格式化时间
    formatTime(timestamp) {
      if (!timestamp) return ''
      
      const date = new Date(timestamp)
      const now = new Date()
      
      // 同一天，只显示时分
      if (date.toDateString() === now.toDateString()) {
        return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
      }
      
      // 不是同一天，显示月日时分
      return `${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    },
    
    // 滚动到底部
    scrollToBottom() {
      const messageList = this.$refs.messageList
      if (messageList) {
        messageList.scrollTop = messageList.scrollHeight
      }
    },
    
    // 关闭WebSocket连接
    closeConnection() {
      this.$closeWebSocket()
    },
    
    // 处理登出
    handleLogout() {
      this.$confirm('确定要退出登录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$closeWebSocket()
        this.$store.dispatch('logout')
        this.$router.push('/')
      }).catch(() => {})
    },
    
    // 更新用户头像
    async updateUserAvatar(event) {
      const file = event.target.files[0]
      if (!file) return
      
      try {
        // 显示上传中提示
        const loadingInstance = this.$loading({
          lock: true,
          text: '头像上传中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        
        // 上传文件
        const res = await fileApi.upload(file)
        
        // 更新头像样式
        this.userAvatarStyle = {
          backgroundImage: `url(${formatImageUrl(res.url)})`,
          backgroundSize: 'cover',
          backgroundPosition: 'center',
          color: 'transparent'
        }
        
        // 保存到本地存储
        localStorage.setItem('userAvatar', res.url)
        
        // 关闭上传提示
        loadingInstance.close()
        
        // 显示成功提示
        this.$message.success('头像更新成功')
        
        // 清空文件输入，允许重复选择同一文件
        this.$refs.avatarUploader.value = ''
      } catch (error) {
        console.error('更新用户头像失败:', error)
        this.$message.error('更新用户头像失败')
      } finally {
        // 关闭对话框
        this.showAvatarUploadDialog = false
      }
    },
    
    // 处理命令
    handleCommand(command) {
      if (command === 'resetExitChoice') {
        trayManager.resetExitChoice();
        this.$message.success('退出选项已重置，下次关闭窗口时将重新询问');
      }
    },
    
    // 设置额外的本地用户列表更新，作为后备保障
    setupUserListUpdate() {
      this.userListUpdateInterval = setInterval(async () => {
        try {
          const userList = await userApi.getUserList()
          this.$store.dispatch('updateUserList', userList)
        } catch (error) {
          console.error('更新用户列表失败:', error)
        }
      }, 10000)
    },
    
    // 清除本地用户列表更新定时器
    clearUserListUpdate() {
      clearInterval(this.userListUpdateInterval)
    },
    
    // 添加用户交互事件监听，在用户操作时更新用户列表
    setupUserInteractionListeners() {
      // 保存方法的绑定版本，以便在移除时使用
      this._boundUpdateUserListOnInteraction = this.updateUserListOnInteraction.bind(this);
      
      // 监听主要用户交互
      document.addEventListener('mousedown', this._boundUpdateUserListOnInteraction);
      document.addEventListener('touchstart', this._boundUpdateUserListOnInteraction);
      document.addEventListener('keydown', this._boundUpdateUserListOnInteraction);
    },
    
    // 移除用户交互事件监听
    removeUserInteractionListeners() {
      if (this._boundUpdateUserListOnInteraction) {
        document.removeEventListener('mousedown', this._boundUpdateUserListOnInteraction);
        document.removeEventListener('touchstart', this._boundUpdateUserListOnInteraction);
        document.removeEventListener('keydown', this._boundUpdateUserListOnInteraction);
      }
    },
    
    // 用户交互时更新用户列表（节流处理，确保不会频繁更新）
    updateUserListOnInteraction: function() {
      if (this._userListUpdateDebounce) {
        clearTimeout(this._userListUpdateDebounce);
      }
      
      this._userListUpdateDebounce = setTimeout(() => {
        if (this.$updateUserList) {
          this.$updateUserList();
        }
      }, 3000); // 3秒内只会触发一次
    },
    
    // 添加解锁音频的事件监听器
    setupAudioUnlockListeners() {
      // 各种用户交互事件，用于解锁音频
      const unlockEvents = ['mousedown', 'touchstart', 'keydown'];
      
      const unlockHandler = () => {
        console.log('用户交互触发，尝试解锁音频');
        // 调用websocket模块中的解锁函数
        this.$ws.unlockAudio();
        
        // 一定时间后移除这些事件监听，以避免不必要的重复调用
        setTimeout(() => {
          unlockEvents.forEach(event => {
            document.removeEventListener(event, unlockHandler);
          });
          console.log('音频解锁事件监听已移除');
        }, 5000);
      };
      
      // 添加各种事件监听
      unlockEvents.forEach(event => {
        document.addEventListener(event, unlockHandler);
      });
      
      console.log('音频解锁事件监听已设置');
    },
    
    // 切换声音状态
    toggleSound() {
      this.soundEnabled = !this.soundEnabled;
      
      // 保存声音状态到localStorage，方便下次打开应用时保持用户的选择
      localStorage.setItem('soundEnabled', this.soundEnabled ? 'true' : 'false');
      
      // 显示状态变化提示
      this.$message({
        message: this.soundEnabled ? '通知声音和弹窗已开启' : '通知声音和弹窗已关闭',
        type: this.soundEnabled ? 'success' : 'warning',
        duration: 2000
      });
    },
    
    // 处理Enter键按下事件
    handleEnterPress(event) {
      // 如果按下了Shift键，不发送消息（用于换行）
      if (event.shiftKey) {
        return;
      }
      
      // 阻止默认行为（换行）
      event.preventDefault();
      
      // 发送消息
      this.sendTextMessage();
    }
  }
}
</script>

<style scoped>
.chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7f9;
}

.header {
  height: 60px;
  background-color: #409EFF;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.logo {
  font-size: 20px;
  font-weight: bold;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-info .avatar-container {
  position: relative;
  cursor: pointer;
  margin-right: 15px;
  transition: transform 0.3s;
}

.user-info .avatar-container:hover {
  transform: scale(1.05);
}

.user-info .user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #67C23A;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: bold;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
}

.user-info .avatar-hover-text {
  position: absolute;
  bottom: -20px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 12px;
  color: white;
  background-color: rgba(0, 0, 0, 0.6);
  padding: 2px 6px;
  border-radius: 10px;
  opacity: 0;
  transition: opacity 0.3s;
  white-space: nowrap;
}

.user-info .avatar-container:hover .avatar-hover-text {
  opacity: 1;
}

.user-info .username-text {
  margin-right: 15px;
  font-weight: bold;
}

.user-info .el-button {
  margin-left: 10px;
}

.main {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.user-list {
  width: 250px;
  background-color: white;
  border-right: 1px solid #e6e6e6;
  overflow-y: auto;
}

.user-item {
  height: 60px;
  display: flex;
  align-items: center;
  padding: 0 15px;
  cursor: pointer;
  transition: all 0.3s;
  border-bottom: 1px solid #f5f7f9;
}

.user-item:hover {
  background-color: #f5f7f9;
}

.user-item.active {
  background-color: #ecf5ff;
  border-left: 3px solid #409EFF;
}

.user-item.notification {
  background-color: rgba(255, 0, 0, 0.05);
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #909399;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 10px;
  font-weight: bold;
}

.online-avatar {
  background-color: #409EFF;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.offline-avatar {
  background-color: #909399;
  opacity: 0.8;
}

.group-avatar {
  background-color: #67C23A;
  box-shadow: 0 0 0 2px rgba(103, 194, 58, 0.2);
}

.user-info {
  flex: 1;
}

.username {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
  color: #303133;
}

.status {
  font-size: 12px;
  color: #909399;
}

.status.online {
  color: #67C23A;
}

.divider {
  height: 36px;
  display: flex;
  align-items: center;
  padding: 0 15px;
  background-color: #f5f7f9;
  color: #606266;
  font-size: 13px;
  font-weight: 500;
  border-top: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #f5f7f9;
}

.chat-header {
  height: 60px;
  background-color: white;
  display: flex;
  align-items: center;
  padding: 0 20px;
  border-bottom: 1px solid #e6e6e6;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.message-list {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.no-message {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #909399;
  font-size: 14px;
}

.message-item {
  display: flex;
  margin-bottom: 20px;
}

.message-item.self {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #409EFF;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 10px;
  font-weight: bold;
}

.message-item.self .message-avatar {
  margin-right: 0;
  margin-left: 10px;
  background-color: #67C23A;
}

.message-content {
  max-width: 70%;
}

.message-info {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.message-item.self .message-info {
  flex-direction: row-reverse;
}

.message-sender {
  font-size: 14px;
  font-weight: bold;
  color: #303133;
  margin-right: 10px;
}

.message-item.self .message-sender {
  margin-right: 0;
  margin-left: 10px;
}

.message-time {
  font-size: 12px;
  color: #909399;
}

.message-text {
  background-color: white;
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  word-break: break-all;
  text-align: left;
}

.message-item.self .message-text {
  background-color: #ecf5ff;
  color: #409EFF;
}

.message-image img {
  max-width: 300px;
  max-height: 200px;
  border-radius: 5px;
  cursor: pointer;
}

.message-file {
  background-color: white;
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.message-emoji {
  font-size: 24px;
}

.input-area {
  padding: 10px;
  background-color: white;
  border-top: 1px solid #e6e6e6;
  position: relative;
}

.toolbar {
  display: flex;
  margin-bottom: 10px;
}

.toolbar i {
  font-size: 20px;
  color: #909399;
  margin-right: 15px;
  cursor: pointer;
  transition: color 0.3s;
}

.toolbar i:hover {
  color: #409EFF;
}

.emoji-picker {
  position: absolute;
  bottom: 100%;
  left: 10px;
  background-color: white;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 10px;
  display: flex;
  flex-wrap: wrap;
  width: 300px;
  z-index: 10;
}

.emoji-item {
  font-size: 24px;
  margin: 5px;
  cursor: pointer;
  transition: transform 0.3s;
}

.emoji-item:hover {
  transform: scale(1.2);
}

.send-button {
  text-align: right;
  margin-top: 10px;
}

.avatar-upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.current-avatar {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.avatar-preview {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background-color: #409EFF;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 40px;
  font-weight: bold;
  margin-bottom: 10px;
}

.upload-options {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.upload-options p {
  margin-bottom: 15px;
}

.upload-options .tip {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}
</style> 